package mahan.test.data.mongodb;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.Date;
import java.util.Map;

import mahan.data.core.Util;
import mahan.data.model.CartLineItem;
import mahan.data.model.ShoppingCart;
import mahan.data.mongodb.MahanDB;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

public class ShoppingCartTestCase {
	private MahanDB mahanDb;

	@After
	public void clean() {
		mahanDb.get().dropDatabase();
	}

	@Before
	public void setup() {
		mahanDb = new MahanDB("localhost", 27017, "cartdb");
		DB db = mahanDb.get();
		assertNotNull(db);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Test
	public void testCart() throws Exception {
		Date date = new Date();
		ShoppingCart cart = new ShoppingCart(1);
		CartLineItem item1 = new CartLineItem();
		item1.setProductID(111);
		item1.setSellingPrice(23.99);
		item1.setAdded(date);
		item1.setItemType("M");
		item1.setSize(2.0);
		cart.add(item1);

		CartLineItem item2 = new CartLineItem();
		item2.setProductID(211);
		item2.setSellingPrice(53.99);
		item2.setAdded(date);
		cart.add(item2);

		assertEquals(2, cart.getItems().size());
		assertEquals(77.98, Util.total(cart), 0.01);

		// Store into DB
		BasicDBObject dbo = new BasicDBObject();
		dbo.putAll(cart.get());
		DBCollection coll = mahanDb.createCollection("cust");
		coll.save(dbo);

		// Retrieve from DB
		DBObject fromDB = coll.findOne();
		Map dbMap = fromDB.toMap();
		int cid = (Integer) dbMap.get("cid");
		ShoppingCart from = new ShoppingCart(cid);
		from.put(fromDB.toMap());
		assertEquals(1, cid);
		assertEquals(2, from.getItems().size());
		assertEquals(77.98, Util.total(from), 0.01);

		// Test JSON
		JSONObject jsonObj = from.json();
		JSONArray arr = (JSONArray) jsonObj.get("i");
		assertEquals(2, arr.length());
	}
}